#include <iostream>
#include <string>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include <functional>

typedef websocketpp::server<websocketpp::config::asio> wssrvr_t;   

void wsopen_callback(wssrvr_t* server, websocketpp::connection_hdl hdl)
{
    std::cout<<"握手成功！"<<std::endl;
}

void wsclose_callback(wssrvr_t* server, websocketpp::connection_hdl hdl)
{
    std::cout<<"连接断开!"<<std::endl;
}

void wsmessage_callback(wssrvr_t* server, websocketpp::connection_hdl hdl, wssrvr_t::message_ptr msg)
{
    wssrvr_t::connection_ptr con = server->get_con_from_hdl(hdl);
    std::cout<<"client msg:"<<msg->get_payload()<<std::endl;
    std::string str = "server echo:" + msg->get_payload();
    con->send(str,websocketpp::frame::opcode::text);
}

void wshttp_callback(wssrvr_t* server, websocketpp::connection_hdl hdl)
{
    wssrvr_t::connection_ptr con = server->get_con_from_hdl(hdl);
    std::cout<<"body:"<<con->get_request_body()<<std::endl;
    websocketpp::http::parser::request req = con->get_request();
    std::cout<<"method:"<<req.get_method()<<std::endl;
    std::cout<<"uri:"<<req.get_uri()<<std::endl;

    std::string str = "<html><body><h1>hello world</h1></body></html>";
    con->set_status(websocketpp::http::status_code::value::ok);
    con->set_body(str);
    con->append_header("Content-Type","text/html");

}



int main()
{
    //1.实例化server对象
    wssrvr_t server;
    //2.设置日志等级
    server.set_access_channels(websocketpp::log::alevel::none);
    //3.初始化asio调度器
    server.init_asio();
    server.set_reuse_addr(true);
    //4.设置回调函数
    server.set_open_handler(std::bind(wsopen_callback,&server,std::placeholders::_1));//websocket握⼿成功回调处理函数
    server.set_close_handler(std::bind(wsclose_callback,&server,std::placeholders::_1));//websocket连接关闭回调处理函数
    server.set_message_handler(std::bind(wsmessage_callback,&server,std::placeholders::_1,std::placeholders::_2));//websocket消息回调处理函数
    server.set_http_handler(std::bind(wshttp_callback,&server,std::placeholders::_1));//http请求回调处理函数
    //5.设置监听窗口
    server.listen(8080);    
    //6.开始获取新连接
    server.start_accept();
    //7.启动服务器
    server.run();

    return 0;
}